/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.sql.DataSource;
import ru.ssau.entities.DataAccessException;


public class EntityUtil {

    private static final String REQUEST_USER_ID_SEQUENCE_GET_NEXT_VALUE =
            "SELECT UserIDSeq.NEXTVAL FROM dual";
    private static final String REQUEST_THREAD_ID_SEQUENCE_GET_NEXT_VALUE =
            "SELECT ThreadIDSeq.NEXTVAL FROM dual";
    private static final String REQUEST_MESSAGE_ID_SEQUENCE_GET_NEXT_VALUE =
            "SELECT MessageIDSeq.NEXTVAL FROM dual";
    private static final String REQUEST_AUTHORIZATION_INFO_ID_SEQUENCE_GET_NEXT_VALUE =
            "SELECT AuthInfoIDSeq.NEXTVAL FROM dual";

    private EntityUtil() {
        
    }

    private static Integer getIdFromQuery(String queryString) throws DataAccessException {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            DataSource ds = DatabaseUtil.getDataSource();
            conn = ds.getConnection();
            ps = conn.prepareStatement(queryString);
            ResultSet rs = ps.executeQuery();
            if(rs.next()) {
                throw new DataAccessException("Cannot generate id for user");
            }
            return Integer.valueOf(rs.getInt(1));
        } catch(SQLException ex) {
            throw new DataAccessException(ex);
        } catch(NamingException ex) {
            throw new DataAccessException("Cannot find data source", ex);
        }
    }

    public static Integer getUserIdSequenceNextValue() throws DataAccessException {
        return getIdFromQuery(REQUEST_USER_ID_SEQUENCE_GET_NEXT_VALUE);
    }

    public static Integer getThreadIdSequenceNextValue() throws DataAccessException {
        return getIdFromQuery(REQUEST_THREAD_ID_SEQUENCE_GET_NEXT_VALUE);
    }

    public static Integer getMessageIdSequenceNextValue() throws DataAccessException {
        return getIdFromQuery(REQUEST_MESSAGE_ID_SEQUENCE_GET_NEXT_VALUE);
    }

    public static Integer getAuthorizationInfoIdSequenceNextValue() throws DataAccessException {
        return getIdFromQuery(REQUEST_AUTHORIZATION_INFO_ID_SEQUENCE_GET_NEXT_VALUE);
    }

}
